package com.tour.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.IService;
import com.tour.config.ResponseWrapper;
import com.tour.entity.SComment;
import com.tour.entity.Shop;
import com.tour.mapper.SCommentMapper;
import com.tour.mapper.ShopMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;

import java.text.DecimalFormat;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author lel
 * @since 2021-03-30
 */
@Service
public class SCommentServiceImpl extends ServiceImpl<SCommentMapper, SComment> implements IService<SComment> {

    @Autowired
    SCommentMapper sCommentMapper;
    @Autowired
    ShopMapper shopMapper;

    public ResponseWrapper addsComment(@RequestBody SComment sComment){
        if (sComment == null){
            return ResponseWrapper.markError();
        }else {
            int result = sCommentMapper.insert(sComment);
            if (result == 1){
                int sid = sComment.getSId();
                Shop shop = shopMapper.selectById(sid);
                QueryWrapper<SComment> sCommentQueryWrapper = new QueryWrapper<>();
                sCommentQueryWrapper.eq("s_id",sid);
                List<SComment> sCommentList = sCommentMapper.selectList(sCommentQueryWrapper);
                int score = 0;
                for (SComment sComments : sCommentList){
                    score +=Integer.valueOf((int) Double.parseDouble(sComments.getSScore()));
                }
                DecimalFormat df = new DecimalFormat("0.0");
                float scores = Float.valueOf(df.format(score));
                float relscore = Float.valueOf(scores/sCommentList.size());
                String relscores = df.format(relscore);
                System.out.println(relscores);
                shop.setSScore(relscores);
                shopMapper.updateById(shop);
                return ResponseWrapper.markSuccess(null);
            }else {
                return ResponseWrapper.markError();
            }
        }
    }
    public ResponseWrapper dleleteComment(Integer scId){
        if (scId == null){
            return ResponseWrapper.markError();
        }else {
            int result = sCommentMapper.deleteById(scId);
            if (result == 1){
                return ResponseWrapper.markSuccess(null);
            }else {
                return ResponseWrapper.markError();
            }
        }
    }

}
